package com.stillalive.mq.mqserver.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.stillalive.mq.common.ConsumerEnv;
import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Getter
@Setter
public class MSGQueue {
    // 队列的身份标识
    private String name;
    // 队列是否持久化,true表示持久化保存，false表示不持久化
    private boolean durable = false;
    // 为true，表示这个队列只能被一个消费者使用（是否独有）
    private boolean exclusive = false;
    // 是否自动删除
    private boolean autoDelete = false;
    // 扩展参数
    private Map<String, Object> arguments = new HashMap<>();
    // 当前队列有哪些消费者订阅
    private List<ConsumerEnv> consumerEnvList = new ArrayList<>();
    // 记录当前取到了第几个消费者
    private AtomicInteger consumerSeq = new  AtomicInteger(0);

    // 添加一个新的订阅者
    public void addConsumerEnv(ConsumerEnv consumerEnv) {
        synchronized (this) {
            consumerEnvList.add(consumerEnv);
        }
    }
    // 挑选一个订阅者来处理当前的消息（轮询）
    public ConsumerEnv chooseConsumer(){
        // 当前队列没有人订阅
        if(consumerEnvList.size() == 0){
            return null;
        }
        // 计算一下当前要取的元素的下标
        int index = consumerSeq.get() % consumerEnvList.size();
        consumerSeq.getAndIncrement();
        return consumerEnvList.get(index);
    }
    public String getArguments(){
        ObjectMapper argumentsMapper = new ObjectMapper();
        try {
            return argumentsMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "{}";
    }
    // 收到的参数按照Json格式解析，转成Map对象
    public void setArguments(String argumentsJson){
        ObjectMapper argumentsMapper = new ObjectMapper();
        try {
            this.arguments = argumentsMapper.readValue(argumentsJson, new TypeReference<HashMap<String, Object>>() {});
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
    public void setArguments(Map<String, Object> arguments){
        this.arguments = arguments;
    }

    // 这组get和set仅是方便测试
    public Object getArguments(String key){
        return arguments.get(key);
    }
    public void setArguments(String key, Object value){
        arguments.put(key, value);
    }
}
